//
//  SetViewController.m
//  WuLi
//
//  Created by Gollum on 16/9/2.
//  Copyright © 2016年 Gollum. All rights reserved.
//

#import "SetViewController.h"
#import "SetImageTableViewCell.h"
#import "SetSwitchTableViewCell.h"

#import "FeedbackViewController.h"
#import "UserAgreementViewController.h"
#import "CoverViewController.h"
#import "VersionInformationViewController.h"
#import "UIImageView+WebCache.h"
#import "SDImageCache.h"
#import "DKNightVersion.h"
#define kSetImageTableViewCell @"setImage"
#define kSetSwitchTableViewCell @"setSwitch"


@interface SetViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong)SetImageTableViewCell *cell;
@property (weak, nonatomic) IBOutlet UIButton *quitButton;
@property (nonatomic,strong)NSArray *section1;
@property (nonatomic,strong)NSArray *section2;
@property (nonatomic,strong)NSArray *section3;

@property (weak, nonatomic) IBOutlet UILabel *pageTitle;
@property (nonatomic,strong)NSUserDefaults *userDefaults;
@property (nonatomic,copy)NSString *imageUrl;

@property (nonatomic,copy)NSString *path;

@end

@implementation SetViewController

- (void)viewWillAppear:(BOOL)animated{

    _userDefaults = [NSUserDefaults standardUserDefaults];
    _imageUrl = [_userDefaults objectForKey:@"userImageUrl"];
    if (_imageUrl) {
        _quitButton.alpha = 1.f;
    }else{
        _quitButton.alpha = 0.f;
      
    }



}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    _path = [_path stringByAppendingPathComponent:@"Caches"];
    
    
    self.view.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:0.26 green:0.26 blue:0.34 alpha:1.00]);

    _pageTitle.dk_textColorPicker = DKColorWithColors([UIColor blackColor], [UIColor whiteColor]);
    
   
    _section1 = @[@"字体大小", @"夜间模式"];
    _section2 = @[@"推送通知"];
    _section3 = @[@"意见反馈", @"用户协议", @"清除缓存", @"唔哩封面", @"版本更新", @"版本信息"];
    _quitButton.clipsToBounds = YES;
    _quitButton.layer.cornerRadius = 25;
    
    _tableView.rowHeight = 50;
    _tableView.bounces = NO;
    _tableView.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor grayColor]);
    
    [_tableView registerNib:[UINib nibWithNibName:@"SetImageTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kSetImageTableViewCell];
    
    [_tableView registerNib:[UINib nibWithNibName:@"SetSwitchTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kSetSwitchTableViewCell];
    
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 20;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView *view = [[UIView alloc] init];
    view.dk_backgroundColorPicker = DKColorWithColors([UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00], [UIColor colorWithRed:0.26 green:0.26 blue:0.34 alpha:1.00]);
    return view;
}
- (IBAction)handleBack:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{


    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (section == 0) {
        return 2;
    }else if (section == 1){
        return 1;
    }else{
    
        return 6;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            SetImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSetImageTableViewCell];
            cell.labelContent.text = @"中";
            cell.title.text = _section1[indexPath.row];
            


            return cell;
        }else{
            SetSwitchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSetSwitchTableViewCell];
            cell.title.text = _section1[indexPath.row];

            [cell.switchButton addTarget:self action:@selector(handleNightSwitch:) forControlEvents:UIControlEventValueChanged];
            #pragma mark - 判断switch的状态
            if ([[NSUserDefaults standardUserDefaults] boolForKey:@"ISNIGHT"]) {
                cell.switchButton.on = YES;
            }else {
                cell.switchButton.on = NO;
                
            }
            return cell;
        }
    }
    
    
    else if (indexPath.section == 1){
        SetSwitchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSetSwitchTableViewCell];
        cell.title.text = _section2[indexPath.row];

        return cell;

    }
    
    
    else{

    SetImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSetImageTableViewCell];
        cell.title.text = _section3[indexPath.row];

        if (indexPath.row == 2) {
            
    cell.labelContent.text = [NSString stringWithFormat:@"%.2fM", [self floderSizeAtPath:self.path]];
            
        }else{
        cell.labelContent.text = @" ";
        }
    return cell;
    
    }
    
    
}
- (void)handleNightSwitch:(UISwitch*)nightSwitch{

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    if ([DKNightVersionManager currentThemeVersion] == DKThemeVersionNight) {
        [DKNightVersionManager dawnComing];
    } else {
        [DKNightVersionManager nightFalling];
    }
    // 保存状态 , 程序再次启动时的偏好设置
    [user setBool:nightSwitch.on forKey:@"ISNIGHT"];
    [user synchronize];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SwitchChange" object:nil userInfo:@{@"switch" : @(nightSwitch.on)}];

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
            {
            
            
            }
                break;
            case 2:{
            
            
            }
                break;
                
            default:
                break;
        }
    }
    
    
    
    if (indexPath.section == 2) {
        switch (indexPath.row) {
                //意见反馈
            case 0:{
                FeedbackViewController *feedBack = [[FeedbackViewController alloc] init];
                [self presentViewController:feedBack animated:YES completion:^{
                    
                }];
            
            }
                break;
                //用户协议
            case 1:{
                UserAgreementViewController *userAgreement = [[UserAgreementViewController alloc] init];
                [self presentViewController:userAgreement animated:YES completion:^{
                    
                }];
            
            }
                break;
                //清除缓存
            case 2:{
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否清除缓存" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    [self clearAction];
                
                }];
                
                UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alert addAction:actionCancel];
                [alert addAction:actionOK];
                //  模态推出.
                [self presentViewController:alert animated:YES completion:^{}];
                
//                NSString *path = [SDImageCache sharedImageCache].diskCachePath;
                
                
                
//                NSLog(@"%@",path);
                
                
                
                
            }
                break;
                //封面
            case 3:{
                CoverViewController *cover = [[CoverViewController alloc] init];
                [self presentViewController:cover animated:YES completion:^{
                    
                }];
            }
                break;
                //版本更新
            case 4:{
            
                
            }
                break;
                //版本信息
            case 5:{
                
                VersionInformationViewController *versionInformation = [[VersionInformationViewController alloc] init];
                
                [self presentViewController:versionInformation animated:YES completion:^{
                    
                }];
            
            }
                break;
                
            default:
                break;
        }
    }


}

- (IBAction)quitButton:(id)sender {
    NSString*appDomain = [[NSBundle mainBundle]bundleIdentifier];
    
    [[NSUserDefaults standardUserDefaults]removePersistentDomainForName:appDomain];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}

// 计算缓存大小
- (long long)fileSizeAtPath:(NSString *)path {
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        return [[manager attributesOfItemAtPath:path error:nil] fileSize];
    }
    return 0;
}
- (float)floderSizeAtPath:(NSString *)path {
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) {
        return 0;
    }else {
        NSEnumerator *enumerator = [[manager subpathsAtPath:path] objectEnumerator];
        NSString *fileName = [NSString string];
        CGFloat floderSize = 0;
        while ((fileName = [enumerator nextObject]) != nil) {
            NSString *absolutPath = [path stringByAppendingPathComponent:fileName];
            floderSize += [self fileSizeAtPath:absolutPath];
        }
        
        return floderSize/ 1024/ 1024;
    }
    
    return 0;
}
- (void)clearAction {
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    path = [path stringByAppendingPathComponent:@"Caches"];
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        NSArray *fileNameArr = [manager subpathsAtPath:path];
        for (NSString *fileName in fileNameArr) {
            NSString *absoltPath = [path stringByAppendingPathComponent:fileName];
            [manager removeItemAtPath:absoltPath error:nil];
        }
    }
    [_tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
